package com.htthorizon.util;

import com.htthorizon.common.core.exception.ServiceException;
import okhttp3.*;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.TimeUnit;

/**
 * 封装 OkHttpClient
 *
 * @author mark
 * @date 2023-11-15
 */
public class HttpRequestUtils {

    private static final OkHttpClient client;
    private static final int HTTP_SUCCESS_CODE = 200;

    static {
        client = new OkHttpClient.Builder()
                .connectTimeout(5, TimeUnit.SECONDS)
                .readTimeout(5, TimeUnit.SECONDS)
                .build();
    }

    public static String get(String url) throws IOException {
        Request request = new Request.Builder()
                .get()
                .url(url)
                .build();
        return execute(request);
    }

    public static String post(String url, RequestBody requestBody) throws IOException {
        Request request = new Request.Builder()
                .post(requestBody)
                .url(url)
                .build();
        return execute(request);
    }

    public static String post(String url, Map<String,Object> params) throws IOException {
        Request request = new Request.Builder()
                .post(createRequestBody(params))
                .url(url)
                .build();
        return execute(request);
    }

    public static String get(String url, Map<String,Object> params) throws IOException {
        return request("GET", url, params);
    }

    /**
     * 发送http请求
     *
     * @param method 请求方法
     * @param url    地址
     * @param params 参数
     * @return 请求结果
     */
    public static String request(String method, String url, Map<String, Object> params) {
        if (method == null) {
            throw new RuntimeException("请求方法不能为空");
        }
        if (url == null) {
            throw new RuntimeException("url不能为空");
        }
        if (!url.startsWith("http://") && !url.startsWith("https://")) {
            throw new ServiceException("URL is not an HTTP or HTTPS request");
        }
        HttpUrl.Builder httpBuilder = HttpUrl.parse(url).newBuilder();
        if (params != null) {
            for (Map.Entry<String, Object> param : params.entrySet()) {
                httpBuilder.addQueryParameter(param.getKey(), param.getValue().toString());
            }
        }
        Request request = null;
        if("GET".equals(method)){
            request = new Request.Builder()
                    .url(url)
                    .build();
        }else{
            request = new Request.Builder()
                    .url(httpBuilder.build())
                    .method(method, new FormBody.Builder().build())
                    .build();
        }
        try {
            OkHttpClient client = new OkHttpClient.Builder()
                    .readTimeout(20, TimeUnit.SECONDS)
                    .build();
            Response response = client.newCall(request).execute();
            int responseCode = response.code();
            if (responseCode == HTTP_SUCCESS_CODE) {
                ResponseBody body = response.body();
                if (body == null) {
                    return null;
                }else {
                    return body.string();
                }
            }
            throw new ServiceException(String.format("http request failed,code=%d", responseCode));
        } catch (IOException e) {
            return null;
        }
    }


    public static String postJson(String url, String json) throws IOException {
        MediaType jsonType = MediaType.parse("application/json; charset=utf-8");
//        RequestBody requestBody = RequestBody.create(json, jsonType);
        RequestBody requestBody = null;
        return post(url, requestBody);
    }

    public static RequestBody createRequestBody(Map<String,Object> params) throws IOException {
        FormBody.Builder builder = (new FormBody.Builder());
        if (params != null && params.size() > 0) {
            for (String key:params.keySet()){
                Optional<String> optionalS = Optional.ofNullable(params.get(key).toString());
                if(optionalS.isPresent()) {
                    builder.add(key, optionalS.get());
                }
            }
        }
        return builder.build();
    }

    private static String execute(Request request) throws IOException {
        try (Response response = client.newCall(request).execute()) {
            int responseCode = response.code();
            if (responseCode == HTTP_SUCCESS_CODE) {
                ResponseBody body = response.body();
                if (body == null) {
                    return null;
                }else {
                    return body.string();
                }
            }
            throw new ServiceException(String.format("http request failed,code=%d", responseCode));
        }
    }

    public static void main(String[] args) {
        String str = request("DELETE","http://127.0.0.1:18081/manage/model/source/32", null);
        System.out.println(str);
    }
}
